<template>
  <div class="dicInset_dlg">
    <el-dialog
      title="数据字典"
      :visible.sync="dialogDicVisible"
      width="70%"
      top="50px"
      :before-close="handleDicClose"
      custom-class="dragDialog"
      v-dialogDrag>
      <el-form class="rule-form" ref="form" :model="ruleForm" :rules="rules">
        <el-form-item label="医院" label-width="80px" prop="hospitalCode">
          <el-select style="width:100%" size="small" filterable v-model="ruleForm.hospitalCode" @change="changeHosp" placeholder="请选择医院">
            <el-option
              v-for="item in mx_hospitalList"
              :key="item.code"
              :label="item.name"
              :value="item.code"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="类型" label-width="80px" prop="type">
          <!-- <el-autocomplete
            size="small"
            style="width:100%"
            v-model="ruleForm.type"
            :fetch-suggestions="querySearch"
            placeholder="请输入或选择类型"
          ></el-autocomplete> -->
          <el-select
            size="small"
            v-model="ruleForm.type"
            placeholder="请选择"
            clearable
            filterable
            allow-create
            :disabled="!!ruleForm.id"
            style="width:100%">
            <el-option
              v-for="(item,index) in typeOptions"
              :key="index"
              :label="item.value"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="影像区域" label-width="80px" prop="depArea">
          <el-select style="width:100%" size="small" v-model="ruleForm.depArea" @change="changeDepArea" placeholder="请选择" clearable>
            <el-option
              v-for="item in depAreaOptions"
              :key="item"
              :label="item"
              :value="item"
            ></el-option>
          </el-select>
        </el-form-item>
        <!-- <el-form-item label="科室" label-width="80px" prop="department">
        <el-select style="width:100%" size="small" v-model="ruleForm.department" placeholder="请选择" clearable>
          <el-option
            v-for="item in departmentOptions"
            :key="item"
            :label="item"
            :value="item"
          ></el-option>
        </el-select>
      </el-form-item> -->
        <el-form-item label="检查部门" label-width="80px" prop="dep">
          <el-select style="width:100%" size="small" v-model="ruleForm.dep" @change="changeDep" placeholder="请选择" clearable>
            <el-option
              v-for="item in depOptions"
              :key="item"
              :label="item"
              :value="item"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="设备类型" label-width="80px" prop="modality">
          <el-select style="width:100%" size="small" v-model="ruleForm.modality" placeholder="请选择" clearable>
            <el-option
              v-for="item in modalityOptions"
              :key="item"
              :label="item"
              :value="item"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="项目" label-width="80px" prop="item">
          <el-input size="small" v-model="ruleForm.item" clearable @change="itemChange"></el-input>
        </el-form-item>
        <el-form-item label="项目拼音" label-width="80px" prop="itemPy">
          <el-input size="small" v-model="ruleForm.itemPy" clearable></el-input>
        </el-form-item>
        <el-form-item label="项目值" label-width="80px" prop="itemValue">
          <el-input type="textarea" size="small" v-model="ruleForm.itemValue" clearable :rows="8"></el-input>
        </el-form-item>
        <el-form-item label="排序" label-width="80px" prop="sortid" v-if="ruleForm.id">
          <el-input size="small" type="number" v-model="ruleForm.sortid" clearable></el-input>
        </el-form-item>
        <el-form-item :label="ruleForm.type === '注意事项' && dialogDicVisible ? '注意事项': '备注1'" label-width="80px" prop="remark">
          <AppEditor
            v-if="ruleForm.type === '注意事项' && dialogDicVisible"
            id="appEditor2"
            :content.sync="ruleForm.remark"
          />
          <el-input v-if="ruleForm.type !== '注意事项'" type="textarea" size="small" v-model="ruleForm.remark" clearable></el-input>
        </el-form-item>
        <el-form-item :label="ruleForm.type === '注意事项' && dialogDicVisible ? '检查须知': '备注2'" label-width="80px" prop="remark2">
          <AppEditor
            v-if="ruleForm.type === '注意事项' && dialogDicVisible"
            id="appEditor3"
            :content.sync="ruleForm.remark2"
          />
          <el-input v-if="ruleForm.type !== '注意事项'" type="textarea" size="small" v-model="ruleForm.remark2" clearable></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button size="small" @click="handleDicClose">关 闭</el-button>
        <el-button size="small" type="primary" @click="handleDicConfirm('form')">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import { getDepAreaList, getDepList, getModalityTypeList, getTypeGroupList, updateItemList, insertItemList, getItemList } from '@/api/api.js'
// import paginationCont from '@/components/Pagination/index'
import { Options } from '@/utils/constant'
import AppEditor from '@/components/appEditor'

export default {
  name: 'DicInsertDialog',
  components: {
    AppEditor
  },
  props: {
    dialogDicVisible: {
      type: Boolean,
      default: false
    },
    dicData: {
      type: Object,
      default: null
    }
  },
  data() {
    return {
      options: Options,
      typeOptions: [], //
      departmentOptions: [], // 科室
      depAreaOptions: [],
      depOptions: [], // 检查部门
      modalityOptions: [], // 检查设备
      ruleForm: {
        id: null,
        hospitalCode: '',
        type: '',
        depArea: '',
        department: '',
        dep: '',
        modality: '',
        item: '',
        itemPy: '',
        itemValue: '',
        sortid: '',
        remark: '',
        remark2: ''
      },
      totalCount: 0,
      pageSize: 10,
      currentPage: 1,
      tableDic: [],
      rules: {
        hospitalCode: [{ required: true, message: '请选择医院', trigger: 'blur' }],
        type: [{ required: true, message: '请选择类型', trigger: 'blur' }],
        item: [{ required: true, message: '请填写项目', trigger: 'blur' }]
      }
    }
  },
  watch: {
    dialogDicVisible: {
      immediate: true,
      async handler(val) {
        if (val) {
          this.$refs.form && this.$refs.form.clearValidate()
          this.ruleForm.id = null
          await this.$getHospitalList()
          this.handleReset()
          if (this.dicData) {
            this.ruleForm = Object.assign(this.ruleForm, this.dicData)
          }
          this.init()
        }
      }
    }
  },
  created() {
  },
  methods: {
    async init() {
      try {
        this.getDepArea()
        this.getDep()
        this.getType()
        this.getCheckList()
      } catch (err) {
        console.log(err)
      }
    },
    async changeHosp() {
      if (!this.ruleForm.hospitalCode) return
      // 关联：影像、检查部门、检查分组、检查设备、检查机房
      this.depAreaOptions = []
      this.depOptions = []
      this.typeOptions = []
      this.modalityOptions = []
      this.ruleForm.depArea = ''
      this.ruleForm.dep = ''
      this.ruleForm.type = ''
      this.ruleForm.modality = ''

      try {
        this.getDepArea()
        this.getDep()
        this.getType()
        this.getCheckList()
      } catch (err) {
        console.log(err)
      }
    },
    getDepArea() {
      let data = { HospitalCode: this.ruleForm.hospitalCode }
      return new Promise(async resolve => {
        await getDepAreaList(data).then(res => {
          if (res && res.code === 10000) {
            this.depAreaOptions = res.content.list
            resolve(res)
          }
        })
      })
    },
    getType() {
      return new Promise(async resolve => {
        await getTypeGroupList(this.ruleForm).then(res => {
          if (res && res.code === 10000) {
            this.typeOptions = res.content.list.map(item => { return { value: item } })
            resolve(res)
          }
        })
      })
    },
    getDepartment() {
      let data = {
        HospitalCode: this.ruleForm.hospitalCode,
        DepArea: this.ruleForm.depArea,
        type: '科室'
      }
      return new Promise(async resolve => {
        await getItemList(data).then(res => {
          if (res && res.code === 10000) {
            this.departmentOptions = res.content.list.map(_item => _item.item)
            resolve(res)
          }
        })
      })
    },
    async changeDepArea() {
      // if (!this.ruleForm.depArea) return
      // 关联：检查部门 科室
      this.depOptions = []
      this.modalityOptions = []
      this.ruleForm.dep = ''
      this.ruleForm.modality = ''

      try {
        await this.getDep()
        await this.getCheckList()
      } catch (err) {
        console.log(err)
      }
    },
    getDep() {
      let data = {
        HospitalCode: this.ruleForm.hospitalCode,
        DepArea: this.ruleForm.depArea
      }
      return new Promise(async resolve => {
        await getDepList(data).then(res => {
          if (res && res.code === 10000) {
            this.depOptions = res.content.list
            resolve(res)
          }
        })
      })
    },
    async changeDep() {
      // if (!this.ruleForm.dep) return
      // 关联：检查分组、检查设备、检查机房
      this.modalityOptions = []
      this.ruleForm.modality = ''

      try {
        await this.getCheckList()
      } catch (err) {
        console.log(err)
      }
    },
    getCheckList() {
      let data = {
        HospitalCode: this.ruleForm.hospitalCode,
        Dep: this.ruleForm.dep
      }
      return new Promise(async resolve => {
        await getModalityTypeList(data).then(res => {
          if (res && res.code === 10000) {
            this.modalityOptions = res.content.list
            resolve(res)
          }
        })
      })
    },
    handleDicClose() {
      this.$emit('myClose')
    },
    handleDicConfirm(formName) {
      this.$refs[formName].validate((valid, object) => {
        if (valid) {
          // 修改
          if (this.ruleForm.sortid || this.ruleForm.sortid === 0) {
            this.ruleForm.sortid = this.ruleForm.sortid + ''
          }
          if (this.ruleForm.id) {
            updateItemList(this.ruleForm).then(res => {
              if (res && res.code === 10000) {
                this.$message.success('修改成功')
                this.$emit('refreshDic')
              }
            })
          } else {
            insertItemList(this.ruleForm).then(res => {
              if (res && res.code === 10000) {
                this.$message.success('添加成功')
                this.$emit('refreshDic')
              }
            })
          }
        } else {
          for (let k in object) {
            this.$message.warning(object[k][0].message)
            return
          }
        }
      })
    },
    querySearch(queryString, cb) {
      var types = this.typeOptions
      var results = queryString ? types.filter(this.createFilter(queryString)) : types
      // 调用 callback 返回建议列表的数据
      cb(results)
    },
    createFilter(queryString) {
      return (types) => {
        return (types.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0)
      }
    },
    handleReset() {
      const resetForm = {
        id: null,
        hospitalCode: '',
        type: '',
        depArea: '',
        department: '',
        dep: '',
        modality: '',
        item: '',
        itemPy: '',
        itemValue: '',
        sortid: '',
        remark: '',
        remark2: ''
      }
      this.ruleForm = Object.assign(this.ruleForm, resetForm)
    },
    itemChange() {
      if (this.ruleForm.item) {
        this.ruleForm.itemPy = window.pinyinUtil.getFirstLetter(this.ruleForm.item, false).toUpperCase()
      } else {
        this.ruleForm.itemPy = ''
      }
    }
  }
}
</script>
<style lang="scss" scoped>
.dicInset_dlg{
    /deep/ .el-dialog__body{
        padding: 10px 20px;
        height: calc(100vh - 220px);
        overflow-y: auto;
    }
    .el-form{
        .el-form-item{
            margin-bottom: 10px;
            /deep/ .el-form-item__error{
                padding-top: 0px;
            }
        }
    }
}
</style>
